
layui.use(['element', 'layedit', 'jquery', 'layer', 'util','laytpl'], function() {
	var element = layui.element,
		layedit = layui.layedit,
		$ = layui.jquery,
		util=layui.util,
		laytpl = layui.laytpl,
		layer = layui.layer;

	//构建一个默认的编辑器
	var leavemessage_index = layedit.build('blog-editor',{
		height:150,
		tool:['strong','italic','underline','del','|', 'face','|','link']
	});


	/**
	 * 递归遍历子结点数组,同时处理时间(如：’几分钟前‘)
	 * @param nodes  子结点数组
	 * @param array  存放所有结点的数组引用
	 */
	var loadChildNode=function (nodes,array) {
		if (nodes.length==0) {
			return;
		}
		for (let i = 0; i < nodes.length; i++) {
			nodes[i].commentTime=util.timeAgo(nodes[i].commentTime);
			array.push(nodes[i]);
			loadChildNode(nodes[i].childNode, array);
		}
	}

	/**
	 * 页面加载时，请求加载留言
	 */
	var loadComments =function() {
		$.getJSON("/comment/list",function (res) {
			// console.log(res);
			if(res.data.length==0){
				$("#message-display").append("<li id='noData'>暂无数据！</li>");
				return;
			}
			var parentNodeList=layui.sort(res.data,'commentTime',true)
			layui.each(parentNodeList, function (parent_index, parent_item) {
				//对父评论集进行按时间降序排序，即最新时间在前面
				parent_item.commentTime=util.timeAgo(parent_item.commentTime);
				//渲染父评论
				laytpl($("#message-parent-tpl").html()).render(parent_item, function (html) {
					$("#message-display").append(html);
				});
				var childNodeList = [];   //存放该父评论下的所有子评论
				loadChildNode(parent_item.childNode, childNodeList);  //递归子评论数组
				//按照commentId字段降序排序
				childNodeList=layui.sort(childNodeList,'commentId',true);
				// console.log(childNodeList);  //打印所有子评论
				//渲染子评论
				layui.each(childNodeList, function (child_index, child_item) {
					laytpl($("#message-child-tpl").html()).render(child_item, function (html) {
						$("#commentId-"+parent_item.commentId).after(html);
					});
				});
			});
		});
	}
	loadComments();

	// alert(layedit.getContent(index)); //获取编辑器内容
	/**
	 * 	留言提交事件
	 */
	$('#btn-submit-message').on('click', function() {
		var content = layedit.getContent(leavemessage_index);
		if(content.length==0){
			layer.msg("不打字就算了,至少给个表情包吧！",{icon:5,anim:6,time:2000});
			return;
		}
/*		if(content.length>600){
			layer.msg("200个字符以内哦！",{icon:5,anim:1,time:2000});
			return ;
		}*/
		$.ajax({
			url:'/comment/add',
			type:'post',
			headers:{
				"Authorization": $.cookie("access_token")
			},
			data:JSON.stringify({'content':content}),
			contentType:'application/json',
			dataType:'json',
			success:function (res) {
				// console.log(res);
				if (res.code == 0) {
					res.data.commentTime=util.timeAgo(res.data.commentTime);
					layer.msg("留言成功",{icon:1,anim:1,time:1000},function () {
						//渲染父评论
						laytpl($("#message-parent-tpl").html()).render(res.data, function (html) {
							$("#noData").hide();
							$("#message-display").prepend(html);
							//清空layui富文本编辑器
							$("#LAY_layedit_1").contents().find('body').html('');
						});
					});
				}
				else{
					layer.msg(res.msg,{icon:2,anim:6,time:1500});
				}
			}
		});
	});

	/**
	 * 点击回复按钮的事件
	 * @param parentId   回复的评论ID
	 * @param toUserName  回复的用户
	 */
	window.reply = function(parentId,toUserName) {
		var reply_index;
		layer.open({
			type: 1,
			content: '<div style="margin:10px"><textarea class="layui-textarea" id="reply" style="display: none;"></textarea></div>',
			title: "正在回复" + toUserName,
			btn: '提交',
			anim: 1,
			area: ['350px', '270px'],
			maxmin: true,
			yes: function(index) {
				var content=layedit.getContent(reply_index);
				if(content.length==0){
					return ;
				}
				if(content.length>600){
					layer.msg("200个字符以内哦！",{icon:5,anim:1,time:2000});
					return ;
				}

				//发送到后台的数据
				var data= {
					"content": content ,
					"parentId": parentId
				};
				$.ajax({
					url:'/comment/add',
					type:'post',
					headers: {
						"Authorization":$.cookie("access_token")
					},
					data:JSON.stringify(data),
					contentType:'application/json',
					dataType:'json',
					success:function (res) {
						if (res.code == 0) {
							//处理响应数据的时间，即某个时间在当前时间的多久前
							res.data.commentTime=util.timeAgo(res.data.commentTime);
							layer.msg("回复成功",{icon:1,anim:1,time:1000},function () {
								//渲染回复评论
								laytpl($("#message-child-tpl").html()).render(res.data, function (html) {
									$("#commentId-" + parentId).parent().append(html);
								});
							});
							layer.close(index);
						}
						else{
							layer.msg(res.msg,{icon:2,anim:6,time:1500});
						}
					}
				});
			},
			success: function() {
				//弹窗弹出后的回调，初始化回复文本框
				reply_index=layedit.build('reply', {
					height: 100,
					tool: ['strong','italic','underline','del','|', 'face','|','link']
				});
			}
		});
	};

});
